"""
创建用户脚本
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from sqlalchemy.orm import sessionmaker
from passlib.context import CryptContext
from app.database import engine
from app.models import Employee, Department

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def create_user():
    """创建新用户"""
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        print("=== CRM系统用户创建工具 ===")
        print()
        
        # 获取部门列表
        departments = session.query(Department).all()
        if not departments:
            print("错误: 没有找到部门，请先运行数据库初始化脚本")
            return
        
        print("可用部门:")
        for i, dept in enumerate(departments, 1):
            print(f"{i}. {dept.name}")
        print()
        
        # 获取用户输入
        employee_no = input("请输入员工编号: ").strip()
        if not employee_no:
            print("错误: 员工编号不能为空")
            return
        
        # 检查员工编号是否已存在
        existing_employee = session.query(Employee).filter(Employee.employee_no == employee_no).first()
        if existing_employee:
            print(f"错误: 员工编号 '{employee_no}' 已存在")
            return
        
        name = input("请输入员工姓名: ").strip()
        if not name:
            print("错误: 员工姓名不能为空")
            return
        
        # 选择部门
        while True:
            try:
                dept_choice = int(input("请选择部门 (输入数字): ")) - 1
                if 0 <= dept_choice < len(departments):
                    selected_department = departments[dept_choice]
                    break
                else:
                    print("错误: 请输入有效的部门编号")
            except ValueError:
                print("错误: 请输入数字")
        
        position = input("请输入职位 (可选): ").strip()
        phone = input("请输入手机号 (可选): ").strip()
        email = input("请输入邮箱 (可选): ").strip()
        
        # 设置密码
        while True:
            password = input("请输入密码: ").strip()
            if len(password) < 6:
                print("错误: 密码长度不能少于6位")
                continue
            
            confirm_password = input("请确认密码: ").strip()
            if password != confirm_password:
                print("错误: 两次输入的密码不一致")
                continue
            
            break
        
        # 创建用户
        new_employee = Employee(
            employee_no=employee_no,
            name=name,
            department_id=selected_department.id,
            position=position or None,
            phone=phone or None,
            email=email or None,
            password_hash=pwd_context.hash(password),
            status="active"
        )
        
        session.add(new_employee)
        session.commit()
        
        print()
        print("✅ 用户创建成功！")
        print(f"员工编号: {employee_no}")
        print(f"员工姓名: {name}")
        print(f"所属部门: {selected_department.name}")
        print(f"职位: {position or '未设置'}")
        print(f"手机号: {phone or '未设置'}")
        print(f"邮箱: {email or '未设置'}")
        print()
        
    except Exception as e:
        session.rollback()
        print(f"❌ 创建用户时出错: {e}")
    finally:
        session.close()


def list_users():
    """列出所有用户"""
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        employees = session.query(Employee).all()
        
        if not employees:
            print("没有找到任何用户")
            return
        
        print("=== 用户列表 ===")
        print(f"{'ID':<5} {'员工编号':<15} {'姓名':<10} {'部门':<15} {'职位':<15} {'状态':<8}")
        print("-" * 80)
        
        for emp in employees:
            dept_name = emp.department.name if emp.department else "未知"
            status_text = "在职" if emp.status == "active" else "离职"
            print(f"{emp.id:<5} {emp.employee_no:<15} {emp.name:<10} {dept_name:<15} {emp.position or '未设置':<15} {status_text:<8}")
        
        print()
        
    except Exception as e:
        print(f"❌ 获取用户列表时出错: {e}")
    finally:
        session.close()


def change_password():
    """修改用户密码"""
    Session = sessionmaker(bind=engine)
    session = Session()
    
    try:
        employee_no = input("请输入要修改密码的员工编号: ").strip()
        if not employee_no:
            print("错误: 员工编号不能为空")
            return
        
        employee = session.query(Employee).filter(Employee.employee_no == employee_no).first()
        if not employee:
            print(f"错误: 找不到员工编号为 '{employee_no}' 的用户")
            return
        
        print(f"找到用户: {employee.name} ({employee.employee_no})")
        
        # 设置新密码
        while True:
            new_password = input("请输入新密码: ").strip()
            if len(new_password) < 6:
                print("错误: 密码长度不能少于6位")
                continue
            
            confirm_password = input("请确认新密码: ").strip()
            if new_password != confirm_password:
                print("错误: 两次输入的密码不一致")
                continue
            
            break
        
        # 更新密码
        employee.password_hash = pwd_context.hash(new_password)
        session.commit()
        
        print("✅ 密码修改成功！")
        
    except Exception as e:
        session.rollback()
        print(f"❌ 修改密码时出错: {e}")
    finally:
        session.close()


def main():
    """主菜单"""
    while True:
        print()
        print("=== CRM系统用户管理工具 ===")
        print("1. 创建新用户")
        print("2. 查看用户列表")
        print("3. 修改用户密码")
        print("0. 退出")
        print()
        
        choice = input("请选择操作 (0-3): ").strip()
        
        if choice == "1":
            create_user()
        elif choice == "2":
            list_users()
        elif choice == "3":
            change_password()
        elif choice == "0":
            print("再见！")
            break
        else:
            print("错误: 请输入有效的选项 (0-3)")


if __name__ == "__main__":
    main()
